/**
 * 
 */
package com.real.fact.web.product.application;

import java.text.DecimalFormat;
import java.util.List;

import org.apache.commons.lang.Validate;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.globant.katari.core.application.Command;
import com.globant.katari.core.application.JsonRepresentation;
import com.real.fact.web.application.RealPaging;
import com.real.fact.web.product.domain.Product;
import com.real.fact.web.product.domain.ProductRepository;

/**
 *
 */
public class SearchProductCommand implements Command<JsonRepresentation>{

  private final ProductRepository productRepository;
  
  private String query;

  public SearchProductCommand(ProductRepository productRepository) {
    Validate.notNull(productRepository, "Product repository can not be null.");
    this.productRepository = productRepository;
  }

  public String getQuery() {
    return query;
  }

  public void setQuery(String query) {
    this.query = query;
  }

  public JsonRepresentation execute() {
    try {
    DecimalFormat formatter = new DecimalFormat("0.00");
    List<Product> result = productRepository.findByName(query, new RealPaging());
    JSONObject resultSet = new JSONObject();
    JSONArray array = new JSONArray();
    for (Product p : result) {
      
      JSONObject object = new JSONObject();
      object.put("id", p.getId());
      object.put("name", p.getName());
      object.put("brand", p.getBrand());
      object.put("category", p.getCategory());
      object.put("price", formatter.format(p.getDeskPrice()));
      object.put("stock", formatter.format(p.getStock()));
      array.put(object);
      
    }
    resultSet.put("Result", array);
    return new JsonRepresentation(resultSet);
    } catch (JSONException e) {
      throw new RuntimeException("Error searching products", e);
     }
  }

}
